PHP: Page views meter
November 12, 2020
require_once (dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'functions_counters.php');
// Call functions_counters.php
counter_page_views_db(); // Define database path
counter_page_views_increment(); // Add 1 to database for every new page view
counter_page_views_snippet(); // Display counter as a string
<?php
// page views
function counter_page_views_db(): string
{
$db = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'php-playground' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'counter_page-views' . DIRECTORY_SEPARATOR . 'total.txt';
return $db;
}
function counter_page_views_increment(): void
{
$db = counter_page_views_db();
if (file_exists($db)) {
$views = (int)file_get_contents($db);
$views++;
} else {
$views = 1;
}
file_put_contents($db, $views);
}
function counter_page_views_snippet(): void
{
$db = counter_page_views_db();
$counter_total = file_get_contents($db);
$line = "<b>$counter_total</b> page view";
if ($counter_total !== 1) { $line .= 's'; }; // Use plural only if several views
echo $line;
}